from django.http import Http404

__author__ = 'magnusg08'



from Exams.models import ExamUser,ExamQuestion,Exam,ExamOption,StudentAnswer,StudentExam

#adding to ExamUsers logged in users, used in views.py index function
def check_loginuser(loguser):
    try:
        obj = ExamUser.objects.get(user_name=loguser)
    except ExamUser.DoesNotExist:
        obj = ExamUser(user_name=loguser)
        obj.save()

 # Statistical functions
# Teacher should probably  have access to all stat functions

# lists closed exams, how many participated, how many passed, how many failed, average grade  for each exam
def teacher_stat(user):
    pass


#lists closed exams , students grade in each, average grade in each, + teacher_stat for that exam
def student_stat(user):
    pass


# shows requested exam with students answers , correct answers and students grade
def student_result(user):
    print Exam.objects.all()
    print Exam.objects.all().exclude(studentexam__student=user)



def already_taken_exam(studentid,examid):
    try:
        se = StudentExam.objects.get(exam_id = examid,student = studentid)
    except StudentExam.DoesNotExist:
        print "not taken exam"

def calculate_grade(studentid,examid):
    try:
        q=ExamQuestion.objects.filter(exam_id=examid).count()#number of questions in examid
        # s=contains correct answers rom student studentid in exam examid
        s=ExamOption.objects.filter(exam_question_id__exam_id=examid).filter(is_correct=1).filter(studentanswer__student=studentid)
        grade=s.count()*10/q
    except ZeroDivisionError:
        grade=0
    return grade

def calculate_avgrade(examid):
    tot_grade=0
    e=StudentExam.objects.filter(exam_id=examid)
    n=e.count()
    q=ExamQuestion.objects.filter(exam_id=examid).count()
    for student in e:
        try:
            s=ExamOption.objects.filter(exam_question_id__exam_id=examid).filter(is_correct=1).filter(studentanswer__student=student.student)
            grade=s.count()*10/q
        except ZeroDivisionError:
            grade=0
        tot_grade += grade
    av_grade=tot_grade/n
    return av_grade

def calculate_order(studentid,examid):
    order=1
    studentsgrade=calculate_grade(studentid,examid)
    e=StudentExam.objects.filter(exam_id=examid)
    n=e.count()
    q=ExamQuestion.objects.filter(exam_id=examid).count()
    for student in e:
        try:
            s=ExamOption.objects.filter(exam_question_id__exam_id=examid).filter(is_correct=1).filter(studentanswer__student=student.student)
            grade=s.count()*10/q
        except ZeroDivisionError:
            grade=0
        if grade>studentsgrade:
            order += 1
    return order,n
# returns order from top and number of participants





